const qs = require('qs')
const Mock = require('mockjs')
const config = require('../utils/config')
const {apiPrefix} = config

let usersListData = Mock.mock({
    'data|80-100':[
        {
            id:'@id',
            name: '@name',
            nickName: '@last',
            phone: /^1[34578]\d{9}$/,
            'age|11-99':1,
            address: '@county(true)',
            isMale: '@boolean',
            email: '@email',
            createTime: '@datetime',
            avatar(){
                return Mock.Random.image('100x100',Mock.Random.color(),'#757575','png', this.nickName.substr(0,1))
            },
        }
    ]
});

let database = usersListData.data

const EnumRoleType= {
    ADMIN: 'admin',
    DEFAULT: 'admin',
    DEVELOPER: 'developer',
}

const userPermission = {
    DEFAULT: {
        visit: ['1', '2', '21', '7', '5'],
        role: EnumRoleType.DEFAULT
    },
    ADMIN: {
        role: EnumRoleType.ADMIN
    },
    DEVELOPER:{
        role: EnumRoleType.DEVELOPER
    }
}

const adminUsers = [
    {
        id: 0,
        username: 'admin',
        password: 'admin',
        permissions: userPermission.ADMIN,
    }
]

const menus = [
    {
        id: 1,
        icon: 'laptop',
        name: 'Dashboard',
        router: '/dashboard',
    },
    {
        id: 2,
        bpid: 1,
        name: 'User Manage',
        icon: 'user',
        router: '/users',
    },
]

module.exports = {

    [`POST ${apiPrefix}/user/login`] (req, res) {
        const { username, password } = req.body
        const user = adminUsers.filter((item) => item.username === username)
        if (user.length > 0 && user[0].password === password) {
        const now = new Date()
        now.setDate(now.getDate() + 1)
        res.cookie('token', JSON.stringify({ id: user[0].id, deadline: now.getTime() }), {
            maxAge: 900000,
            httpOnly: true,
        })
            res.json({ success: true, message: 'Ok' })
        } else {
            res.status(400).end()
        }
    },

    [`GET ${apiPrefix}/user`] (req, res) {
        const cookie = req.headers.cookie || ''
        const cookies = qs.parse(cookie.replace(/\s/g, ''), {delimiter:';'})
        const response = {}
        const user = {}
        if(!cookies.token){
            res.status(200).send({message: 'Not Login'})
            return
        }
        const token = JSON.parse(cookies.token)
        if(token){
            response.success = token.dealine > new Date().getTime()
        }
        if(response.success){
            const userItem = adminUsers.filter(_ => _.id == token.id)
            if(userItem.length>0){
                user.permissions = userItem[0].permissions
                user.username = userItem[0].username
                user.id = userItem[0].id
            }
        }
        response.user = user
        res.json(response)
    },
    [`GET ${apiPrefix}/users`](req, res){
        const { query } = req
        let {pageSize, page, ...other} = query
        pageSize = pageSize || 10
        page = page || 1
        let newData = database
        for(let key in other){
            if({}.hasOwnProperty.call(other,key)){
                newData = newData.filter((item) => {
                    if(key === 'address'){
                        console.log(other)
                        console.log(other[key])
                        return other[key].every(iitem => item[key].indexOf(iitem)> -1)
                    }else if(key === 'createTIme'){
                        const start = new Date(other[key][0]).getTime()
                        const end = new Date(other[key][0]).getTime()
                        const now = new Date(item[key]).getTime()

                        if(start && end){
                            return now >= start && now <=end
                        }
                        return true
                    }
                    return String(item[key]).item().indexOf(decodeURI(other[key]).item()) > -1
                })
                return true
            }
        }
        res.status(200).json({
            data: newData.slice((page-1)*pageSize, page*pageSize),
            total: newData.length,
        })
    }

}